package com.frxuexi.park2303.news

import android.app.AlertDialog
import android.content.DialogInterface
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.SearchView.OnQueryTextListener
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.ItemTouchHelper.LEFT
import androidx.recyclerview.widget.ItemTouchHelper.SimpleCallback
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.frxuexi.base.entity.NewsBeanItem
import com.frxuexi.base.mvi.BaseActivity
import com.frxuexi.base.mvi.RequestType
import com.frxuexi.base.mvi.UiState
import com.frxuexi.base.utils.ArouterManager
import com.frxuexi.park2303.R
import com.frxuexi.park2303.databinding.ActivityNewsBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@Route(path = "/app/NewsActivity")
@AndroidEntryPoint
class NewsActivity : BaseActivity<ActivityNewsBinding,NewsIntent,NewsViewModel>() {
    val newsAdapter by lazy { NewsAdapter() }
    val list= mutableListOf<NewsBeanItem>()
    var position=-1

    override fun getVM(): NewsViewModel {
        return viewModels<NewsViewModel>().value
    }

    override fun getBind(): ActivityNewsBinding {
        return ActivityNewsBinding.inflate(layoutInflater)
    }

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        when(it.type){
                            RequestType.DEFAULT->{
                                val items = it.data as Collection<NewsBeanItem>
                                list.clear()
                                list.addAll(items.filter { it.published })
                                newsAdapter.data.clear()
                                newsAdapter.addData(list.sortedByDescending { it.id })
                                newsAdapter.notifyDataSetChanged()
                            }
                            RequestType.ITEM->{
                                val items = it.data as Collection<NewsBeanItem>
                                newsAdapter.data.clear()
                                newsAdapter.addData(items)
                                newsAdapter.notifyDataSetChanged()
                            }
                            RequestType.DELETE->{
                                newsAdapter.data.removeAt(position)
                                newsAdapter.notifyItemRemoved(position)
                            }
                            RequestType.UPDATE->{
                                vm.sendIntent(NewsIntent.getNews)
                            }

                            else -> {}
                        }

                    }

                    else -> {}
                }
            }
        }
    }

    override fun initView() {
        binding.newsRv.apply {
            adapter=newsAdapter
            layoutManager=LinearLayoutManager(this@NewsActivity)
        }

        newsAdapter.setOnItemClickListener { adapter, view, position ->
            ArouterManager.navigation(this,"/app/NewsUpdateActivity","nid",newsAdapter.data.get(position).id.toString())
        }

        newsAdapter.addChildClickViewIds(R.id.new_detail)
        newsAdapter.setOnItemChildClickListener { adapter, view, position ->
            this.position=position
            val item = newsAdapter.data.get(position)
            AlertDialog.Builder(this)
                .setTitle("撤销提醒")
                .setMessage("确定要撤销${item.title}吗？")
                .setPositiveButton("确定",object : DialogInterface.OnClickListener {
                    override fun onClick(dialog: DialogInterface?, which: Int) {
                        vm.sendIntent(NewsIntent.revokeNews(item.id!!))
                    }
                }).setNegativeButton("取消",null)
                .create().show()
        }

        binding.newsAdd.setOnClickListener {
            ArouterManager.navigation(this,"/app/NewsAddActivity")
        }

        binding.newsSv.setOnQueryTextListener(object :OnQueryTextListener{
            override fun onQueryTextSubmit(query: String?): Boolean {
                vm.sendIntent(NewsIntent.getNewsByCon(query!!))
                return true
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                newsAdapter.data.clear()
                newsAdapter.addData(list)
                newsAdapter.notifyDataSetChanged()
                return true
            }
        })

        ItemTouchHelper(object :SimpleCallback(0, LEFT){
            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                return false
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                position = viewHolder.adapterPosition
                vm.sendIntent(NewsIntent.deleteNews(newsAdapter.data.get(position).id!!))
            }

        }).attachToRecyclerView(binding.newsRv)
    }

    override fun onResume() {
        super.onResume()
        vm.sendIntent(NewsIntent.getNews)
    }

}